﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Console.WriteLine("当前主线程:{0}",Thread.CurrentThread.ManagedThreadId.ToString());

            Func<long> ac = xx;

            // AsyncCallback cb = ; //t => Console.WriteLine("执行结果:,AsyncState={0}", t.AsyncState);
            IAsyncResult ir = ac.BeginInvoke(t =>
            {

                Console.WriteLine("回调线程:{0}", Thread.CurrentThread.ManagedThreadId.ToString());

                endxx(t);

                long y = ac.EndInvoke(t);

                Console.WriteLine("计算结果:{0}", y.ToString());

            }, "反反复复");
            //ir.AsyncWaitHandle.WaitOne();
            //while (!ir.IsCompleted)
            //{
            //    Console.WriteLine("请等待异步结果");
            //}

           //long y= ac.EndInvoke(ir);
           //Console.WriteLine("计算结果:{0}",y.ToString());
           //Thread.Sleep(5000);
            Console.WriteLine("调用完毕");
        }

        private long xx()
        {
            Console.WriteLine("当前xx线程:{0}", Thread.CurrentThread.ManagedThreadId.ToString());

            long lr = 0;
            for (int i = 0; i < 999999; i++)
            {
                lr += i;
            }

            Thread.Sleep(2000);

            Console.WriteLine("xx完毕");

            return lr;
        }

        private void endxx(IAsyncResult t)
        {
            
            Console.WriteLine("执行结果:,AsyncState={0}", t.AsyncState);
        }

    }
}
